package ru.spbau.database.group3.parser;

import ru.spbau.database.group3.queryEvaluator.CreateTableInstruction;
import ru.spbau.database.group3.queryEvaluator.Instruction;
import ru.spbau.database.group3.queryEvaluator.ErrorInstruction;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: stas
 * Date: 1/28/13
 * Time: 10:47 PM
 */
public class CreateTableCmd extends abstractCmd {
    public CreateTableCmd() {
        super(StringConstants.CREATE_TABLE);
    }

    @Override
    public Instruction process(String cmd) throws IOException {
        try {
            String tableName = getTableName(cmd);
            List<String> names = getNames(cmd);
            List<String> types = getTypes(cmd);
            return new CreateTableInstruction(tableName, types, names);
        } catch (IndexOutOfBoundsException e) {
            return new ErrorInstruction(e.getMessage());
        }
    }

    private String getTableName(String cmd) {
        int begin = StringConstants.CREATE_TABLE.length();
        int end = cmd.indexOf("(");
        return cmd.substring(begin,end).trim();
    }

    private List<String> getNames(String cmd) {
        String[] nt = cmd.substring(cmd.indexOf("(") + 1, cmd.lastIndexOf(")")).split(",");
        ArrayList<String> names = new ArrayList<String>();
        for(String s : nt) {
            names.add(s.trim().split(" ")[0]);
        }
        return names;

    }

    private List<String> getTypes(String cmd) {
        String[] nt = cmd.substring(cmd.indexOf("(") + 1, cmd.lastIndexOf(")")).split(",");
        ArrayList<String> types = new ArrayList<String>();
        for(String s : nt) {
            types.add(s.trim().split(" ")[1]);
        }
        return types;
    }
}
